<template>
  <input ref="inputRef" type="file" @change="handleFileChange" class="hidden" />
  <div
    class="w-60 h-[95px] mr-4 bg-gray-100 flex flex-col items-center justify-center text-gray-400 bg-no-repeat bg-center"
    @click="() => inputRef?.click()"
  >
    <template v-if="!dialogImageUrl">
      <span>+上传图片</span>
      <span>建议尺寸480 * 200</span>
    </template>
    <img v-else @click.stop="dialogVisible=true" class="w-full h-full " :style="{backgroundImage:`url(${dialogImageUrl})`,backgroundSize:'contain'}" :src="dialogImageUrl" alt="Preview Image" />
  </div>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, useTemplateRef } from 'vue'
import { uploadApi } from '@/api/upload'

const inputRef = useTemplateRef('inputRef')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const imgUrl = defineModel()

const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)
  uploadApi<{url: string}>(formData).then((res) => {
    console.log(res)
    imgUrl.value = 'http://localhost:3000' + res.data.url
  })
  const objectUrl = URL.createObjectURL(file)
  dialogImageUrl.value = objectUrl
}

</script>
